import { useExamplesStore } from "@/store/index.js";
import { getExamplesDataTree } from "@/data/treeData.js";
import router from "@/router";

const baseURL = import.meta.env.VITE_APP_BASE_URL;

const customExamplePageViewsModules = import.meta.glob(
  "@/views/example-pages/*/*/index.vue"
);

export const getCustomExampleViewsModules = () => {
  return customExamplePageViewsModules;
};

/**
 * 动态加载示例数据
 * @param  modules 模块
 * */
export const loadExampleModules = (modules) => {
  return new Promise(async (resolve) => {
    const dataModuleResult = [];
    for (const path in modules) {
      const module = await modules[path]();
      const example = module.default;
      dataModuleResult.push(example);
    }
    resolve(dataModuleResult);
  });
};

/**
 * 动态加载示例数据
 * @param modules 模块
 * */
export const loadExampleModulesSync = (modules) => {
  const dataModuleResult = [];
  for (const path in modules) {
    const module = modules[path]();
    const example = module.default;
    dataModuleResult.push(example);
  }
  return dataModuleResult;
};

export const loadAllExampleModules = () => {
  const { setDataExampleList, setDataTreeList } = useExamplesStore();

  return new Promise(async (resolve) => {
    // -------方式4：通过 自定义页面的方式自由添加示例 --------
    const customViewDataModules = import.meta.glob(
      "@/views/example-pages/*/*/data.js"
    );

    const customDataViewsModuleResult = await loadExampleModules(
      customViewDataModules
    );
    const visibleCustomDataViewsModuleResult =
      customDataViewsModuleResult.filter((x) => x.visible);
  
    
    const registerExampleViewsRouters = (customDataViewsModules) => {
      customDataViewsModules.forEach((item) => {
        const route = {
          name: item.id,
          path: item.routerPath,
          component: customExamplePageViewsModules[item.pagePath],
          meta: {
            title: item.title,
          },
          children: [],
        };
        if (!router.hasRoute(item.id)) {
          router.addRoute(route);
        }
      });
    };

    registerExampleViewsRouters(visibleCustomDataViewsModuleResult);

    // 树形分类对应的模板示例数据
    const TemplateExampleDataList = [
      ...visibleCustomDataViewsModuleResult,
    ];

    // 树形分类数据
    const ExamplesDataTree = getExamplesDataTree(TemplateExampleDataList);
   
    
    setDataTreeList(ExamplesDataTree);
    setDataExampleList(TemplateExampleDataList);

    resolve({
      dataExampleList: TemplateExampleDataList,
      dataTreeList: ExamplesDataTree,
    });
  });
};
